/**
 * 文档项组件
 */

import React, { useCallback, useState } from 'react';
import {
  Heart,
  Trash2,
  Pin,
} from 'lucide-react';
import FileTypeIcon from './FileTypeIcon';
import type { PersonalDocument } from '@/types/document';

// 文档项属性接口
export interface DocumentItemProps {
  document: PersonalDocument;
  isSelected: boolean;
  onSelect: (id: string, selected: boolean) => void;
  onToggleFavorite: (id: string) => void;
  onTogglePin: (id: string) => void;
  onDelete: (id: string) => void;
  onView: (document: PersonalDocument) => void;
}

// 格式化文件大小
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}

// 格式化日期
export function formatDate(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffTime = Math.abs(now.getTime() - date.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays === 1) return '今天';
  if (diffDays === 2) return '昨天';
  if (diffDays <= 7) return `${diffDays} 天前`;
  
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  });
}

// 文档项组件
export default function DocumentItem({
  document,
  isSelected,
  onSelect,
  onToggleFavorite,
  onTogglePin,
  onDelete,
  onView
}: DocumentItemProps) {
  const [showActions, setShowActions] = useState(false);

  const handleCheckboxChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    onSelect(document.id, e.target.checked);
  }, [document.id, onSelect]);

  const handleFavoriteClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    onToggleFavorite(document.id);
  }, [document.id, onToggleFavorite]);

  const handlePinClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    onTogglePin(document.id);
  }, [document.id, onTogglePin]);

  const handleDeleteClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    onDelete(document.id);
  }, [document.id, onDelete]);

  const handleViewClick = useCallback(() => {
    onView(document);
  }, [document, onView]);

  // 列表视图
  return (
    <div
      className={`flex items-center px-4 py-3 hover:bg-accent border-b border-border cursor-pointer group ${
        isSelected ? 'bg-primary/10 border-primary/20' : ''
      }`}
      onClick={handleViewClick}
      onMouseEnter={() => setShowActions(true)}
      onMouseLeave={() => setShowActions(false)}
    >
      {/* 选择框 */}
      <input
        type="checkbox"
        checked={isSelected}
        onChange={handleCheckboxChange}
        onClick={(e) => e.stopPropagation()}
        className="w-4 h-4 text-primary border-input rounded focus:ring-ring mr-3"
      />

      {/* 文件图标 */}
      <FileTypeIcon fileType={document.file_type} size="md" className="mr-3" />

      {/* 文档信息 */}
      <div className="flex-1 min-w-0 max-w-[300px] pr-4">
        <div className="flex items-center space-x-2">
          <h3 className="text-sm font-medium text-foreground truncate flex-1 min-w-0">
            {document.title}
          </h3>
          {document.is_pinned && (
            <Pin className="w-4 h-4 text-primary flex-shrink-0 fill-current" />
          )}
        </div>
        <p className="text-xs text-muted-foreground truncate mt-0.5">
          {document.description || document.filename}
        </p>
      </div>

      {/* 标签 */}
      <div className="flex items-center space-x-1 mr-4 min-w-0">
        {document.tags && document.tags.length > 0 ? (
          <>
            {document.tags.slice(0, 2).map(tag => (
              <span
                key={tag.id}
                className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-accent text-foreground"
                style={{ backgroundColor: tag.color ? `${tag.color}20` : undefined }}
              >
                {tag.name}
              </span>
            ))}
            {document.tags.length > 2 && (
              <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-accent text-foreground">
                +{document.tags.length - 2}
              </span>
            )}
          </>
        ) : null}
      </div>

      {/* 文件大小 */}
      <div className="text-xs text-muted-foreground w-16 text-right mr-4">
        {formatFileSize(document.file_size)}
      </div>

      {/* 创建时间 */}
      <div className="text-xs text-muted-foreground w-20 text-right mr-4">
        {formatDate(document.created_at)}
      </div>

      {/* 操作按钮 */}
      <div className={`flex items-center space-x-1 ${showActions ? 'opacity-100' : 'opacity-0'} transition-opacity`}>
        <button
          onClick={handleFavoriteClick}
              className="w-6 h-6 flex items-center justify-center rounded hover:bg-accent"
              title={document.is_favorite ? '取消收藏' : '收藏'}
            >
              {document.is_favorite ? (
                <Heart className="w-4 h-4 text-destructive fill-current" />
              ) : (
                <Heart className="w-4 h-4 text-muted-foreground" />
              )}
            </button>
            <button
              onClick={handlePinClick}
              className="w-6 h-6 flex items-center justify-center rounded hover:bg-accent"
              title={document.is_pinned ? '取消置顶' : '置顶'}
            >
              {document.is_pinned ? (
                <Pin className="w-4 h-4 text-primary fill-current" />
              ) : (
                <Pin className="w-4 h-4 text-muted-foreground" />
              )}
            </button>
            <button
              onClick={handleDeleteClick}
              className="w-6 h-6 flex items-center justify-center rounded hover:bg-destructive/10"
              title="删除文档"
            >
              <Trash2 className="w-4 h-4 text-destructive" />
        </button>
      </div>
    </div>
  );
}
